package com.jojo.service;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jojo.entity.BasicInfo;
import com.jojo.entity.Result;
import com.jojo.mapper.BasicInfoMapper;
import com.jojo.utils.HttpClientUtil;
import com.jojo.utils.PidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@Service
public class OrderService {

    @Autowired
    private BasicInfoMapper basicInfoMapper;

    /**
     * 一键下单
     */
    public Result oneKeySubmitOrder(BasicInfo basicInfo) throws Exception {
        if (StrUtil.isBlank(basicInfo.getPhone())) {
            return Result.error(-1, "手机号不能为空");
        }
        if (StrUtil.isBlank(basicInfo.getPid())) {
            return Result.error(-1, "商品id/链接不能为空");
        }
        QueryWrapper<BasicInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", basicInfo.getPhone());
        List<BasicInfo> basicInfoList = basicInfoMapper.selectList(queryWrapper);
        if (basicInfoList.isEmpty()) {
            return Result.error(-1, "该手机号没有绑定cookie，请先绑定cookie");
        }
        String cookie = basicInfoList.get(0).getCookie();
        return HttpClientUtil.httpClient(PidUtil.parsePid(basicInfo.getPid()), cookie);
    }

    /**
     * 定时抢购
     */
    public Result timingSubmitOrder(BasicInfo basicInfo) throws Exception {
        if (StrUtil.isBlank(basicInfo.getPhone())) {
            return Result.error(-1, "手机号不能为空");
        }
        if (null == basicInfo.getTime()) {
            return Result.error(-1, "时间不能为空");
        }
        QueryWrapper<BasicInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", basicInfo.getPhone());
        List<BasicInfo> basicInfoList = basicInfoMapper.selectList(queryWrapper);
        if (basicInfoList.isEmpty()) {
            return Result.error(-1, "该手机号没有绑定cookie，请先绑定cookie");
        }
        String cookie = basicInfoList.get(0).getCookie();
        if (HttpClientUtil.checkoutCookie(cookie)) {
            return Result.error(-1, "cookie已失效");
        }
        ThreadUtil.newExecutor(50).execute(() -> {
            handelTask(basicInfo.getTime(), cookie);
        });
        return Result.success(0, "设定成功");
    }

    /**
     * 抢购任务
     */
    public void handelTask(Date dateTime, String cookie) {
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                try {
                    HttpClientUtil.httpClient(cookie);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        timer.schedule(timerTask, dateTime);
    }
}
